#include "touch.h"
#include "esp_log.h"
#include "../hal_config.h"
#include "driver/i2c_master.h"
#include "esp_lcd_panel_io.h"
#include "esp_lcd_panel_vendor.h"
#include "esp_lcd_panel_ops.h"
#include "esp_lcd_touch_ft5x06.h"

const char* HAL_TOUCH_TAG = "touch";

esp_lcd_touch_handle_t tp = NULL;

void hal_touch_init(void) {
    ESP_LOGI(HAL_TOUCH_TAG, "Initializing touch...");

    esp_lcd_panel_io_handle_t tp_io_handle = NULL;
    esp_lcd_panel_io_i2c_config_t tp_io_config = ESP_LCD_TOUCH_IO_I2C_FT5x06_CONFIG();
    tp_io_config.scl_speed_hz = 100000; // 设置 I2C 时钟频率为 100kHz
    // I2C 总线句柄
    i2c_master_bus_handle_t i2c_bus_handle = NULL;
    i2c_master_get_bus_handle(PIN_I2C_PROT, &i2c_bus_handle);
    // Attach the TOUCH to the I2C bus
    ESP_ERROR_CHECK(esp_lcd_new_panel_io_i2c(i2c_bus_handle, &tp_io_config, &tp_io_handle));

    const esp_lcd_touch_config_t tp_cfg = {
        .x_max = LCD_H_RES,
        .y_max = LCD_V_RES,
        .rst_gpio_num = PIN_TOUCH_RST,
        .int_gpio_num = PIN_TOUCH_INT,
        .levels = {
            .reset = 0,
            .interrupt = 0,
        },
        .flags = {
            .swap_xy = 0,
            .mirror_x = 0,
            .mirror_y = 0,
        },
    };
    ESP_ERROR_CHECK(esp_lcd_touch_new_i2c_ft5x06(tp_io_handle, &tp_cfg, &tp));

    ESP_LOGI(HAL_TOUCH_TAG, "Touch initialized.");
}
